/**
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xume.raob.extensions;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.xume.raob.ObjectBuilder;

/**
 * @author Johan Siebens
 */
public class ExtensionMethodIntrospectionResult {

	private static final Map<Class<?>, ExtensionMethodIntrospectionResult> CACHE = new HashMap<Class<?>, ExtensionMethodIntrospectionResult>();

	public static ExtensionMethodIntrospectionResult forBuilder(Class<? extends ObjectBuilder<?>> builderInterface) {
		ExtensionMethodIntrospectionResult result = CACHE.get(builderInterface);
		if (result == null) {
			result = new ExtensionMethodIntrospectionResult();
			Class<?>[] interfaces = builderInterface.getInterfaces();
			for (Class<?> extensionCandidate : interfaces) {
				result.extensionsMethods.putAll(parseExtensions(extensionCandidate));
			}
			CACHE.put(builderInterface, result);
		}
		return result;
	}

	private static Map<Method, ExtensionMethod> parseExtensions(Class<?> clazz) {
		try {
			Map<Method, ExtensionMethod> extensionMethods = new HashMap<Method, ExtensionMethod>();
			Extension annotation = (Extension) clazz.getAnnotation(Extension.class);
			if (annotation != null) {
				Object extension = annotation.value().newInstance();
				Method[] methods = clazz.getDeclaredMethods();
				for (Method builderMethod : methods) {
					extensionMethods.put(builderMethod, new ExtensionMethod(builderMethod, extension));
				}
			}
			return extensionMethods;
		} catch (ExtensionException e) {
			throw e;
		} catch (Exception e) {
			throw new ExtensionException("Failed to parse extension for interface [" + clazz + "]", e);
		}
	}

	private final Map<Method, ExtensionMethod> extensionsMethods;

	private ExtensionMethodIntrospectionResult() {
		this.extensionsMethods = new HashMap<Method, ExtensionMethod>();
	}

	public boolean contains(Method method) {
		return extensionsMethods.containsKey(method);
	}

	public ExtensionMethod get(Method method) {
		return extensionsMethods.get(method);
	}

}
